import { useEffect, useRef, useState, useLayoutEffect, useCallback } from 'react';
import { outerHeight } from '@/util/outerheight';
import Item from './Item';
import styles from './index.module.less';

const ELEMENT_HEIGHT = 40;
const VISIBLE_COUNT = 10;
const BUFFER_SIZE = 6;
const initList: any[] = [];
for (let i = 1; i <= 10000; i++) {
    const obj = { value: i };
    initList.push(obj);
}
export default function VirtualScroll(props: any) {
    // const { Item } = props;
    const [list, setList]  = useState<any[]>(initList);
    const [firstItem, setFirstItem] = useState<number>(0);
    const [lastItem, setLastItem] = useState<number>(0);
    // 区域内只显示10条数据，再加上上下各3条缓冲数据 共创建16个dom
    let timer: any = null;
    // 动态高度
    const [scrollHeight, setScrollHeight] = useState<number>(0);
    const [visibleList, setVisibleList] = useState<any[]>([]);
    // 挂载ref
    const containerRef = useRef(null);
    const itemRef = useRef(null);
    const anchorItem = useRef({});

    useLayoutEffect(() => {
        list.forEach((item, idx) => {
            item.scrollY = idx * ELEMENT_HEIGHT;
        });
        setScrollHeight(list.length * ELEMENT_HEIGHT);
        // setVisibleList()
    }, [list]);


    useLayoutEffect(() => {
        const curList = [...list.slice(firstItem, lastItem)];
        setVisibleList(curList);
    }, [list, firstItem, lastItem]);

    useLayoutEffect(() => {
        // ELEMENT_HEIGHT = outerHeight(itemRef.current);
        // const containerHeight = containerRef.current?.clientHeight ?? 0;
        // VISIBLE_COUNT = Math.ceil(containerHeight / ELEMENT_HEIGHT);
        setLastItem(VISIBLE_COUNT + BUFFER_SIZE + firstItem);
    }, [firstItem]);
    const updateAnchorItem = useCallback(
        (container: any) => {
            const index = Math.floor(container.scrollTop / ELEMENT_HEIGHT);
            const offset = container.scrollTop - ELEMENT_HEIGHT * index;
            anchorItem.current = {
                index,
                offset
            }
        },
        [],
    )
     
    const scroll = useCallback(
        (event: any) => {
            const container = event.target;
            const tempFirst = Math.floor(container.scrollTop / ELEMENT_HEIGHT);
            setFirstItem(tempFirst);
            // 下面搞那么多花里胡哨，都不如上方来得简单
        },
        [list, updateAnchorItem, firstItem],
    )
    return (
        // 容器的高度为400px
        <div onScroll={scroll} ref={containerRef} className={styles.container}>
            {/* 哨兵，用于撑开滚动高度 */}
            <div className={styles.sentry} style={{ transform: `translateY(${scrollHeight}px)` }} ></div>
            {
                visibleList.map((item, idx) => (
                    <div key={idx} style={{transform: `translateY(${item.scrollY}px)`}} className={styles.wrapItem} >
                        <Item ref={itemRef} item={item} index={idx} key={idx} />
                    </div>
                ))
            }
        </div>
    )
}